import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:xview/utils/dimension.dart';

SwiperController _controller = new SwiperController();
_onScroll(metrics){}

class XSwiper extends StatefulWidget {
  Widget Function(BuildContext context, int index)? itemBuilder;
  int itemCount;
  double itemWidth;
  double itemHeight;
  bool loop;
  bool autoplay;
  int autoplayDelay;
  Axis scrollDirection;
  void Function(int)? onIndexChanged;
  void Function(int)? onTap;
  int duration;
  SwiperPlugin? pagination;
  bool outer;
  SwiperController? controller;
  Function onScroll;

  XSwiper({
    this.controller,
    this.itemBuilder,
    this.itemCount = 0,
    this.itemWidth = 345,
    this.itemHeight = 150,
    this.loop = true, // 如果要监听滑动，loop为false,有报错请重新run
    this.autoplay = false,
    this.autoplayDelay = 3000,
    this.scrollDirection = Axis.horizontal,
    this.onIndexChanged,
    this.onTap,
    this.duration = 300,
    this.pagination,
    this.outer = false, // 如果设置为 true ，分页将显示“内容”容器的“外部”
    this.onScroll = _onScroll,
  });

  @override
  State<StatefulWidget> createState() {
    return _xSwiperState();
  }
}

class _xSwiperState extends State<XSwiper> {
  @override
  Widget build(BuildContext context) {
    return NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification notification){
          // 监听滑动过程
          ScrollMetrics metrics = notification.metrics;
          widget.onScroll(metrics);
          return true;
        },
      child: NotificationListener<ScrollEndNotification>(
        onNotification: (endNotification){
          // 监听滑动结束
          return false;
        },
        child: Swiper(
          controller: widget.controller ?? _controller,
          itemWidth: Dimension(context).toPx(widget.itemWidth),
          itemHeight: Dimension(context).toPx(widget.itemHeight),
          itemCount: widget.itemCount,
          loop: widget.loop,
          autoplay: widget.autoplay,
          autoplayDelay: widget.autoplayDelay,
          scrollDirection: widget.scrollDirection,
          onIndexChanged: widget.onIndexChanged,
          onTap: widget.onTap,
          duration: widget.duration,
          pagination: widget.pagination,
          outer: widget.outer,
          itemBuilder: widget.itemBuilder ?? (context,index){
            return Align(
              alignment: Alignment.topCenter,
              child: Container(),
            );
          },
        ),
      )
    );
  }
}
